package com.ruoyi.quartz.task;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.UserOssTask;
import com.ruoyi.system.domain.UserTask;
import com.ruoyi.system.mapper.UserOssTaskMapper;
import com.ruoyi.system.mapper.UserTaskMapper;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.fc20230330.models.*;
import com.aliyun.sdk.service.fc20230330.*;
import com.google.gson.Gson;
import darabonba.core.client.ClientOverrideConfiguration;

/**
 * @Title: com.ruoyi.quartz.task
 * @author: Sunne
 * @date: 2024-12-09 下午3:07
 * @Description: 添加结果至OSS
 */
@Component("Atask")
public class Atask {
    @Autowired
    private UserOssTaskMapper userOssTaskMapper;
    @Autowired
    private UserTaskMapper userTaskMapper;
    @Autowired
    private ISysUserService iSysUserService;

    public void ryMultipleParams() throws Exception {
        //得到所有已GC任务但是未完成oss的任务
        List<UserTask> userTaskList = userOssTaskMapper.selectUserTaskList();
        if (userTaskList != null && userTaskList.size() > 0) {
            for (UserTask userTask : userTaskList) {
                LocalDate currentDate = LocalDate.now();
                String folder = currentDate.getYear()+""+currentDate.getMonthValue()+""+currentDate.getDayOfMonth()+"/";
                SysUser sysUser = iSysUserService.selectUserById(Long.parseLong(userTask.getCreateBy()));
                String savepath = sysUser.getUserName()+"/"+folder+userTask.getName();
                FileSaveDownDto dto =new FileSaveDownDto();
                dto.setSavepath(savepath);
                dto.setDownpath(userTask.getVideoUrl());
                UserOssTask userOssTask = new UserOssTask();
                userOssTask.setOssurl("https://aivitts.oss-cn-shanghai.aliyuncs.com/"+savepath);
                userOssTask.setTaskid(userTask.getId());
                userOssTask.setVideoUrl(userTask.getVideoUrl());
                userOssTask.setCreateTime(new Date());
                userOssTask.setUpdateTime(new Date());
                userOssTask.setCreateBy(userTask.getCreateBy());
                userOssTask.setUid(Long.parseLong(userTask.getCreateBy()));
                String asyncid = UUID.randomUUID().toString();
                userOssTask.setAsyncid(asyncid);
                Fcli(dto,asyncid);
                userTask.setAsyncQiniu("https://aivitts.oss-cn-shanghai.aliyuncs.com/"+savepath);
                userTask.setQiniuStart("1");
                userOssTaskMapper.insertUserOssTask(userOssTask);
                userTaskMapper.updateUserTask(userTask);
            }
        }
    }
    public void Fcli(FileSaveDownDto dto, String asyncid) throws Exception {
        StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                .accessKeyId("LTAI5tLEqDgixECTnRbXzTS1")
                .accessKeySecret("EVafnha5xj5o5wYxPxQYS3YKyLXjBg")
                .build());
        AsyncClient client = AsyncClient.builder()
                .region("cn-shanghai") // Region ID
                .credentialsProvider(provider)
                .overrideConfiguration(
                    ClientOverrideConfiguration.create()
                    .setEndpointOverride("1800303890024028.cn-shanghai.fc.aliyuncs.com")
                        //.setConnectTimeout(Duration.ofSeconds(30))
                )
                .build();
        Gson gson = new Gson();
        InputStream bodyStream = new ByteArrayInputStream(gson.toJson(dto).getBytes("UTF-8"));
        InvokeFunctionRequest invokeFunctionRequest = InvokeFunctionRequest.builder()
                .functionName("aliserver")
                .qualifier("LATEST")
                .xFcInvocationType("Async")
                .xFcLogType("None")
                .xFcAsyncTaskId(asyncid)
                .body(bodyStream)
                .build();
        CompletableFuture<InvokeFunctionResponse> response = client.invokeFunction(invokeFunctionRequest);
        InvokeFunctionResponse resp = response.get();
        System.out.println(resp.getStatusCode());
        client.close();
    }


}
